<template>
	<div id="mapEl" class="mapEl">
		
	</div>
</template>

<script>
import MapCore from "@arcgis/core/Map"
import PointCore from "@arcgis/core/geometry/Point"
import MapViewCore from "@arcgis/core/views/MapView"
import { mapState, mapMutations, mapActions } from 'vuex'
import { mapTokenStorageKey } from 'common/js/config'
import { getStorage } from 'common/js/utils'
import { spatialReference, baseLods } from './js/map'
import * as mapLayer from './js/mapLayer'

export default {
	emits: ['click', 'zoom-change', 'center-change'],
	props: {
		centerPoint: {
			type: Object,
			default: () => ({
				x: 693287.2590617974,
				y: 2558469.884643247
			})
		}
	},
	computed: {
		...mapState({
			geoserverAccessToken: state => state.BaseMapEl.geoserverAccessToken
		})
	},
	created () {
		this.map = null
		this.mapView = null
    this.getMapToken();
	},
	mounted () {
		this.initMap()
	},
	data () {
		return {
			
		}
	},
	methods: {
		// 增加地图图层
		addLayer (layer) {
			this.mapView.map.add(layer)
		},
		// 坐标转屏幕位置
    toScreen(lng, lat) {
			if (!this.mapView) {
				return
			}

      return this.mapView.toScreen({
        x: lng,
        y: lat,
        spatialReference,
      });
    },
		// 初始化地图
    async initMap() {
			if (!this.geoserverAccessToken) {
				setTimeout(() => {
					this.initMap()
				}, 20)
				return
			}

      if (this.map && this.mapView) {
				return
			}

			this.map = new MapCore({ layers: [
				mapLayer.createLayer_FoShanShiDianZiDiTu2021(),
				mapLayer.createLayer_ShiWaiHeChong()
			]});
			this.mapView = new MapViewCore({
				map: this.map,
				container: 'mapEl',
				zoom: 10,
				center: new PointCore({
					...this.centerPoint,
					spatialReference,
				}),
				constraints: {
					lods: baseLods,
					minZoom: 10,
				},
				theme: {
					accentColor: [255, 0, 155, 0.75],
					textColor: [255, 0, 155, 1],
				},
				spatialReference
			});

			// mapView.on("click", async (e) => {
			// 	this.$emit("click", e);
			// });
			this.mapView.watch('zoom', (e) => {
				this.$emit('zoom-change', e);
			});
			this.mapView.watch('center', (e) => {
				this.$emit('center-change', e);
			});
		},
		async getMapToken () {
      let geoserverTokenData = getStorage(mapTokenStorageKey);
			
      if (
        !geoserverTokenData ||
        new Date().getTime() - geoserverTokenData.createTime >= 43200000
      ) {
        await this.GET_GEOSERVER_ACCESS_TOKEN()
      } else {
        this.SET_GEOSERVER_ACCESS_TOKEN(geoserverTokenData.token);
      }
    },
    ...mapMutations({
      'SET_GEOSERVER_ACCESS_TOKEN': 'BaseMapEl/SET_GEOSERVER_ACCESS_TOKEN',
    }),
    ...mapActions({
      'GET_GEOSERVER_ACCESS_TOKEN': 'BaseMapEl/GET_GEOSERVER_ACCESS_TOKEN',
    }),
	}
}
</script>

<style scoped lang="scss">
.mapEl {
	width: 100%;
	height: 100%;
	overflow: hidden;
	position: relative;
}
</style>
